package fr.aura.launcher.client;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.apache.log4j.Logger;

public class LNCSrvAckMsg  {
	/**
	 * 
	 */
	private static int byteSize=0;
	static Logger logger = Logger.getLogger(LNCSrvAckMsg.class.getName());
	
	LNCSrvMsgHeader hdr;
	byte ackCode[];
	byte msg[];

	public LNCSrvAckMsg() {
		hdr = new LNCSrvMsgHeader();
		ackCode = new byte[4];
	}

	public LNCSrvMsgHeader getHdr() {
		return hdr;
	}

	public void setHdr(LNCSrvMsgHeader hdr) {
		this.hdr = hdr;
	}

	public String getAckCode() {
		String returnValue=null;
		try {
			returnValue = new String(ackCode,"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			logger.error("LNCSrvAckMsg::getAckCode Unable to convert ackCode to ISO-8859-1");
		}
		return returnValue;
	}
	
	public String getMsg() {
		String ackCode = getAckCode();
		String returnValue = null;
		if (ackCode.compareToIgnoreCase("*WCS")==0 || ackCode.compareToIgnoreCase("TWCS")==0 ) {
			try {
				returnValue = new String(msg,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("LNCSrvAckMsg::getMsg Unable to convert message to UTF-8");
			}
		} else {
			try {
				returnValue = new String(msg,"ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				logger.error("LNCSrvAckMsg::getMsg Unable to convert message to ISO-8859-1");
			}
		}
		
		return returnValue.trim();
	}

	
	public byte[] toByteArray() {
		//default buffer endian order is BIG_ENDIAN, which is fine for network transmission
		ByteBuffer myBuffer = ByteBuffer.allocate(byteSize);
		myBuffer.order(ByteOrder.LITTLE_ENDIAN);
		byte headerBytes[] = this.hdr.toByteArray();
		myBuffer.put(headerBytes).put(this.ackCode).put(this.msg);
		return myBuffer.array();
	}
	
	public void fromByteArray(byte[] byteArray) {
		ByteBuffer myBuffer = ByteBuffer.wrap(byteArray);
		myBuffer.order(ByteOrder.LITTLE_ENDIAN);
		
		this.hdr.fromByteArray(myBuffer);
		myBuffer.get(this.ackCode);
		this.msg = new byte[this.hdr.getlSize() - 4];
		myBuffer.get(this.msg);
	}
	
	public int getByteSize() {
		return byteSize;
	}
}
